<template>
  <div id="User">
    <h1 class="page-title">用户信息页面</h1>
    <!-- 查询条件区域 -->
    <div class="search-area">
      <input type="text" placeholder="请输入昵称" v-model="queryParams.name" class="input-field" />
      <input type="text" placeholder="请输入手机号" v-model="queryParams.phone" class="input-field" />
      <input type="text" placeholder="请输入登录账号" v-model="queryParams.loginName" class="input-field" />
      <button @click="fetchUserList" class="btn btn-success">查询</button>
      <button @click="resetQuery" class="btn btn-secondary">重置</button>
    </div>
    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <button @click="showAddModal" class="btn btn-primary">新增</button>
      <button @click="deleteSelectedUsers" class="btn btn-danger" style="margin-left: 10px;">批量删除</button>
    </div>
    <!-- 用户信息列表区域 -->
    <table class="user-table">
      <thead>
      <tr style="height: 60px;">
        <th><input type="checkbox" v-model="isAllChecked" @change="toggleAllCheck" /></th>
        <th>编号</th>
        <th>头像</th>
        <th>昵称</th>
        <th>登录账号</th>
        <th>手机号</th>
        <th>状态(锁定/未锁定)</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="(user, index) in userList" :key="user.userId" class="table-row" style="height: 60px;">
        <!-- 添加条件判断，当userId不为1时才渲染勾选框 -->
        <td v-if="user.userId!== 1"><input type="checkbox" v-model="selectedUserIds" :value="user.userId" /></td>
        <td v-else></td>
        <td>{{ index + 1 }}</td>
        <td><img :src="'/img'+user.avatarImg" alt="Avatar" width="50" height="50" class="avatar-img" /></td>
        <td>{{ user.name }}</td>
        <td>{{ user.loginName }}</td>
        <td>{{ user.phone }}</td>
        <td>{{ user.locked === 0? '未锁定' : '锁定' }}</td>
        <td>
          <button @click="showEditModal(user)" class="btn btn-info">修改</button>
          <button @click="deleteUser(user.userId)" class="btn btn-link btn-danger">删除</button>
        </td>
      </tr>
      </tbody>
    </table>
    <!-- 分页区域 -->
    <!--    <div class="pagination">-->
    <!--      <el-pagination-->
    <!--          @size-change="handleSizeChange"-->
    <!--          @current-change="handleCurrentChange"-->
    <!--          :current-page="currentPage"-->
    <!--          :page-sizes="[5, 10, 20, 30, 40]"-->
    <!--          :page-size="pageSize"-->
    <!--          layout="total, sizes, prev, pager, next, jumper"-->
    <!--          :total="totalCount"-->
    <!--      />-->
    <!--    </div>-->
    <!-- 新增用户模态框 -->
    <el-dialog title="新增用户" :visible.sync="addModalVisible" width="400px">
      <el-form :model="newUser" label-width="80px">
        <el-form-item label="昵称">
          <el-input v-model="newUser.name"></el-input>
        </el-form-item>
        <el-form-item label="登录账号">
          <el-input v-model="newUser.loginName"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="newUser.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <input type="file" @change="handleAddAvatarUpload" />
          <img v-if="newUser.avatarImg" :src="'/img'+newUser.avatarImg" alt="Avatar" width="50" height="50" class="avatar-img" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="newUser.phone"></el-input>
        </el-form-item>
        <el-form-item label="锁定状态">
          <el-select v-model="newUser.locked" placeholder="请选择">
            <el-option label="未锁定" value="0"></el-option>
            <el-option label="锁定" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="newUser.status" placeholder="请选择">
            <el-option label="未删除" value="C001-1"></el-option>
            <el-option label="删除" value="C001-2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addModalVisible = false">取消</el-button>
        <el-button type="primary" @click="addUser">确定</el-button>
      </div>
    </el-dialog>
    <!-- 修改用户模态框 -->
    <el-dialog title="修改用户" :visible.sync="editModalVisible" width="400px">
      <el-form :model="editUser" label-width="80px">
        <el-form-item label="昵称">
          <el-input v-model="editUser.name"></el-input>
        </el-form-item>
        <el-form-item label="登录账号">
          <el-input v-model="editUser.loginName"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="editUser.password"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <input type="file" @change="handleEditAvatarUpload" />
          <img v-if="editUser.avatarImg" :src="editUser.avatarImg" alt="Avatar" width="50" height="50" class="avatar-img" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editUser.phone"></el-input>
        </el-form-item>
        <el-form-item label="锁定状态">
          <el-select v-model="editUser.locked" placeholder="请选择">
            <el-option label="未锁定" value="0"></el-option>
            <el-option label="锁定" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editUser.status" placeholder="请选择">
            <el-option label="未删除" value="C001-1"></el-option>
            <el-option label="删除" value="C001-2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editModalVisible = false">取消</el-button>
        <el-button type="primary" @click="updateUser">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'user',
  components: {},
  props: {},
  data() {
    return {
      queryParams: {
        name: '',
        phone: '',
        loginName: '',
        currentPage: 1,
        pageSize: 5
      },
      userList: [],
      isAllChecked: false,
      selectedUserIds: [],
      currentPage: 1,
      pageSize: 5,
      totalCount: 0,
      addModalVisible: false,
      newUser: {
        name: '',
        loginName: '',
        password: '',
        avatarImg: '',
        phone: '',
        locked: 0,
        status: ''
      },
      editModalVisible: false,
      editUser: {
        userId: 0,
        name: '',
        loginName: '',
        password: '',
        avatarImg: '',
        phone: '',
        locked: 0,
        status: '',
        isAdmin: false
      },
      currentUser: {
        userId: null,
        isAdmin: false
      }
    };
  },
  computed: {},
  methods: {
    async fetchUserList() {
      try {
        console.log('请求参数:', this.queryParams);
        const response = await axios.post('http://localhost:8090/sys-users/user-list', this.queryParams);
        if (response.data.success) {
          this.userList = response.data.userList;
          this.totalCount = response.data.totalCount;
          console.log('用户列表:', this.userList);
          console.log('总记录数:', this.totalCount);
        } else {
          console.error('获取用户列表失败:', response.data.message);
        }
      } catch (error) {
        console.error('请求失败:', error);
      }
    },
    resetQuery() {
      this.queryParams = {
        name: '',
        phone: '',
        loginName: '',
        currentPage: 1,
        pageSize: 5
      };
      this.fetchUserList();
    },
    toggleAllCheck() {
      if (this.isAllChecked) {
        this.userList.forEach(user => {
          if (user.userId!== 1) {
            this.selectedUserIds.push(user.userId);
          }
        });
      } else {
        this.selectedUserIds = [];
      }
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.queryParams.pageSize = size;
      this.fetchUserList();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.queryParams.currentPage = page;
      this.fetchUserList();
    },
    showAddModal() {
      this.addModalVisible = true;
      this.newUser = {
        name: '',
        loginName: '',
        password: '',
        avatarImg: '',
        phone: '',
        locked: 0,
        status: ''
      };
    },
    handleAddAvatarUpload(event) {
      const file = event.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (event) => {
          const img = new Image();
          img.src = event.target.result;
          img.onload = () => {
            const maxWidth = 800;
            const maxHeight = 600;
            let width = img.width;
            let height = img.height;

            if (width > maxWidth) {
              height = height * (maxWidth / width);
              width = maxWidth;
            }

            if (height > maxHeight) {
              width = width * (maxHeight / height);
              height = maxHeight;
            }

            const canvas = document.createElement('canvas');
            canvas.width = width;
            canvas.height = height;
            const ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0, width, height);

            canvas.toBlob((blob) => {
              const reader2 = new FileReader();
              reader2.onload = (e) => {
                this.newUser.avatarImg = e.target.result;
              };
              reader2.readAsDataURL(blob);
            }, file.type, 0.8);
          };
        };
        reader.readAsDataURL(file);
      }
    },
    handleEditAvatarUpload(event) {
      const file = event.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (event) => {
          const img = new Image();
          img.src = event.target.result;
          img.onload = () => {
            const maxWidth = 800;
            const maxHeight = 600;
            let width = img.width;
            let height = img.height;

            if (width > maxWidth) {
              height = height * (maxWidth / width);
              width = maxWidth;
            }

            if (height > maxHeight) {
              width = width * (maxHeight / height);
              height = maxHeight;
            }

            const canvas = document.createElement('canvas');
            canvas.width = width;
            canvas.height = height;
            const ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0, width, height);

            canvas.toBlob((blob) => {
              const reader2 = new FileReader();
              reader2.onload = (e) => {
                this.editUser.avatarImg = e.target.result;
              };
              reader2.readAsDataURL(blob);
            }, file.type, 0.8);
          };
        };
        reader.readAsDataURL(file);
      }
    },
    addUser() {
      // 表单验证
      const phoneRegex = /^1[0-9]{10}$/;
      if (
          this.newUser.name === '' ||
          this.newUser.loginName === '' ||
          this.newUser.password === '' ||
          this.newUser.avatarImg === '' ||
          // 验证手机号格式
          (!phoneRegex.test(this.newUser.phone) || this.newUser.phone === '') ||
          this.newUser.locked === null ||
          this.newUser.status === ''
      ) {
        this.$message.warning('请填写所有必填字段，手机号必须为11位数字！！');
        return;
      }

      axios.post('http://localhost:8090/sys-users/add-user', this.newUser)
          .then(response => {
            if (response.data.success) {
              this.addModalVisible = false;
              this.fetchUserList();
            } else {
              console.error('新增用户失败:', response.data.message);
            }
          })
          .catch(error => {
            console.error('请求失败:', error);
          });
    },
    showEditModal(user) {
      this.editModalVisible = true;
      this.editUser = {
        userId: user.userId,
        name: user.name,
        loginName: user.loginName,
        password: user.password,
        avatarImg: user.avatarImg,
        phone: user.phone,
        locked: user.locked,
        status: user.status,
        isAdmin: user.isAdmin
      };
    },
    updateUser() {
      // 表单验证
      const phoneRegex = /^1[0-9]{10}$/;
      if (
          this.editUser.name === '' ||
          this.editUser.loginName === '' ||
          this.editUser.password === '' ||
          this.editUser.avatarImg === '' ||
          // 验证手机号格式
          (!phoneRegex.test(this.editUser.phone) || this.editUser.phone === '') ||
          this.editUser.locked === null ||
          this.editUser.status === ''
      ) {
        this.$message.warning('请填写所有必填字段，手机号必须为11位数字');
        return;
      }
      // 判断是否为管理员账户（假设管理员账户 userId 为 1）
      // if (this.editUser.userId === 1) {
      //   this.$message.warning('不能修改管理员账户');
      //   return;
      // }

      axios.post('http://localhost:8090/sys-users/update-user', this.editUser)
          .then(response => {
            if (response.data.success) {
              this.editModalVisible = false;
              this.fetchUserList();
            } else {
              console.error('修改用户失败:', response.data.message);
            }
          })
          .catch(error => {
            console.error('请求失败:', error);
          });
    },
    deleteUser(userId) {
      if (userId === 1) {
        this.$message.warning('管理员用户不能删除');
        return;
      }
      this.$confirm('确定要删除该用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.post('http://localhost:8090/sys-users/delete-user', { userId })
            .then(response => {
              if (response.data.success) {
                this.fetchUserList();
              } else {
                console.error('删除用户失败:', response.data.message);
              }
            })
            .catch(error => {
              console.error('请求失败:', error);
            });
      }).catch(() => {
        // 用户取消删除操作
      });
    },
    deleteSelectedUsers() {
      const validUserIds = this.selectedUserIds.filter(id => id!== 1);
      if (validUserIds.length === 0) {
        this.$message.warning('请选择要删除的用户');
        return;
      }
      if (this.selectedUserIds.length!== validUserIds.length) {
        this.$message.warning('id为1的用户不能删除，已排除');
      }
      this.$confirm('确定要批量删除选中的用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.post('http://localhost:8090/sys-users/delete-users', { userIds: validUserIds })
            .then(response => {
              if (response.data.success) {
                this.fetchUserList();
                this.selectedUserIds = [];
                this.isAllChecked = false;
              } else {
                console.error('批量删除用户失败:', response.data.message);
              }
            })
            .catch(error => {
              console.error('请求失败:', error);
            });
      }).catch(() => {
        // 用户取消删除操作
      });
    }
  },
  created() {
    this.fetchUserList();
  },
  mounted() {},
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {}
};
</script>

<style scoped>
/* 全局样式 */
* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
  transition: all 0.3s ease;
}

body {
  font-family: Arial, sans-serif;
  background-color: #f4f4f4;
}

.page-title {
  text-align: center;
  background-color: #007bff;
  color: white;
  padding: 5px;
  font-size: 28px;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

/* 查询条件区域 */
.search-area {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.input-field {
  flex: 1;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 16px;
  margin-right: 5px;
  outline: none;
  transition: border-color 0.3s ease;
}

.input-field:focus {
  border-color: #007bff;
  box-shadow: 0 0 5px rgba(0, 123, 255, 0.2);
}

/* 操作按钮区域 */
.action-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 5px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.btn {
  padding: 12px 25px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease, box-shadow 0.3s ease;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover {
  background-color: #0056b3;
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background-color: #545b62;
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
}

.btn-danger {
  background-color: #dc3545;
  color: white;
}

.btn-danger:hover {
  background-color: #bd2130;
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
}

.btn-link:hover {
  text-decoration: underline;
  color: #0056b3;
}

.btn-info {
  background-color: #17a2b8;
  color: white;
}

.btn-info:hover {
  background-color: #138496;
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
}

/* 用户信息列表区域 */
.user-table {
  width: 100%;
  border-collapse: collapse;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
}

.user-table th,
.user-table td {
  padding: 0px;
  border: 1px solid #e0e0e0;
  text-align: center;
  color: #333;
  font-size: 16px;
}

.table-row:nth-child(even) {
  background-color: #f9f9f9;
}

.table-row:hover {
  background-color: #f0f0f0;
  transform: translateY(-2px); /* 添加轻微的上移动画效果 */
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.08); /* 添加阴影效果 */
}

.avatar-img {
  border-radius: 50%;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}

/* 分页区域 */
.pagination {
  text-align: center;
  margin-top: 20px;
}

/* 对话框样式 */
.el-dialog {
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.el-dialog__title {
  background-color: #007bff;
  color: white;
  padding: 5px;
  font-size: 20px;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.dialog-footer {
  text-align: right;
  padding: 15px;
  border-top: 1px solid #e0e0e0;
}

.el-button {
  /*padding: 10px 20px;*/
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

.el-button--primary {
  background-color: #007bff;
  color: white;
}

.el-button--primary:hover {
  background-color: #0056b3;
}

.el-button--default {
  background-color: #6c757d;
  color: white;
}

.el-button--default:hover {
  background-color: #545b62;
}
</style>
